defmodule Redis.Server do
  use GenServer

  def default_options do
    [
      host: '127.0.0.1',
      port: 6379,
      db: 0,
      password: '',
      reconnect_sleep: 100,
      connect_timeout: 5000
    ]
  end

  def init(options) do
    options = Dict.merge(default_options, options)
    :eredis.start_link(
      options[:host],
      options[:port],
      options[:db],
      options[:password],
      options[:reconnect_sleep],
      options[:connect_timeout]
      )
  end

  def handle_call({:request, request}, _from, client) do
    res = query(client, request)
    {:reply, res, client}
  end

  def handle_cast({:stop}, client) do
    {:stop, :normal, client}
  end

  def terminate(_reason, client) do
    :eredis.stop(client)
    :ok
  end

  defp query(client, command) 
    when is_pid(client) and is_list(command) do
    :eredis.q(client, command)
  end
end
